from django.http import HttpResponse
from . import utils
import json


# 学生登录接口
def login_student(request):
    username = ''
    password = ''
    if request.method == 'GET':
        username = request.GET.get("username")
        password = request.GET.get("password")
    if request.method == 'POST':
        data_json = json.loads(request.body.decode())
        username = data_json.get('username')
        password = data_json.get('password')
    res = utils.login_student(username, password)
    stu = None
    if res[0] == 1003:
        stu = res[1]
        stu['spassword'] = None
    result = {
        "stu": stu,
        "status_code": res[0],
    }
    response = HttpResponse(json.dumps(result))
    response['Access-Control-Allow-origin'] = "*"
    response['Content-Type'] = 'application/json;charset=utf-8'
    return response


# 老师登录接口
def login_teacher(request):
    username = ''
    password = ''
    if request.method == 'GET':
        username = request.GET.get("username")
        password = request.GET.get("password")
    if request.method == 'POST':
        data_json = json.loads(request.body.decode())
        username = data_json.get('username')
        password = data_json.get('password')
    res = utils.login_teacher(username, password)
    tea = None
    if res[0] == 1003:
        tea = res[1]
        tea['tpassword'] = None
    result = {
        "tea": tea,
        "status_code": res[0],
    }
    response = HttpResponse(json.dumps(result))
    response['Access-Control-Allow-origin'] = "*"
    response['Content-Type'] = 'application/json;charset=utf-8'
    return response


# 获取课表接口
def get_course_table(request):
    username = ''
    if request.method == 'GET':
        username = request.GET.get('username')
    elif request.method == 'POST':
        data_json = json.loads(request.body.decode())
        username = data_json.get('username')
    res = utils.get_course_table(username)
    result = {
        "sname": res[0]['sname'],
        "course_table": []
    }
    for item in res:
        item.pop('sname')
        course_time = item['course_time']
        item.pop('course_time')
        sections = utils.split_course_time(course_time)
        item['sections'] = sections
        result['course_table'].append(item)
    response = HttpResponse(json.dumps(result))
    response['Access-Control-Allow-origin'] = "*"
    response['Content-Type'] = 'application/json;charset=utf-8'
    return response


# 获取成绩接口
def get_score(request):
    username = ''
    if request.method == 'GET':
        username = request.GET.get('username')
    elif request.method == 'POST':
        data_json = json.loads(request.body.decode())
        username = data_json.get('username')
    res = utils.get_score(username)
    # 返回结果对象
    result = {
        "sname": res[0]['sname'],
        "score_list": {
            "big_1_up": {
                "score": [],
                "GPA": 0.0
            },
            "big_1_down": {
                "score": [],
                "GPA": 0.0
            },
            "big_2_up": {
                "score": [],
                "GPA": 0.0
            },
            "big_2_down": {
                "score": [],
                "GPA": 0.0
            },
            "big_3_up": {
                "score": [],
                "GPA": 0.0
            },
            "big_3_down": {
                "score": [],
                "GPA": 0.0
            },
            "big_4_up": {
                "score": [],
                "GPA": 0.0
            },
            "big_4_down": {
                "score": [],
                "GPA": 0.0
            },
        }
    }
    index = ['big_1_up', 'big_1_down', 'big_2_up', 'big_2_down', 'big_3_up', 'big_3_down', 'big_4_up', 'big_4_down']
    gpa_score_all = [0, 0, 0, 0, 0, 0, 0, 0]
    credit_all = [0, 0, 0, 0, 0, 0, 0, 0]
    # 处理成绩信息
    for it in res:
        if it['score'] != None:

            it.pop('sname')
            it.pop('tname')
            it.pop('enro_year')
            it.pop('termname')
            if it['termno'] == '1' or it['termno'] == '2':
                # 大一上
                it.pop('termno')
                it['GPA'] = utils.get_GPA1(int(it['score']))
                result['score_list']['big_1_up']['score'].append(it)
                gpa_score_all[0] += float(it['GPA']) * float(it['credit'])
                credit_all[0] += float(it['GPA'])
            elif it['termno'] == '3':
                # 大一下
                it.pop('termno')
                it['GPA'] = utils.get_GPA1(int(it['score']))
                result['score_list']['big_1_down']['score'].append(it)
                gpa_score_all[1] += float(it['GPA']) * float(it['credit'])
                credit_all[1] += float(it['credit'])
            elif it['termno'] == '4' or it['termno'] == '5':
                # 大二上
                it.pop('termno')
                it['GPA'] = utils.get_GPA1(int(it['score']))
                result['score_list']['big_2_up']['score'].append(it)
                gpa_score_all[2] += float(it['GPA']) * float(it['credit'])
                credit_all[2] += float(it['credit'])
            elif it['termno'] == '6':
                # 大二下
                it.pop('termno')
                it['GPA'] = utils.get_GPA1(int(it['score']))
                result['score_list']['big_2_down']['score'].append(it)
                gpa_score_all[3] += float(it['GPA']) * float(it['credit'])
                credit_all[3] += float(it['credit'])
            elif it['termno'] == '7' or it['termno'] == '8':
                # 大三上
                it.pop('termno')
                it['GPA'] = utils.get_GPA1(int(it['score']))
                result['score_list']['big_3_up']['score'].append(it)
                gpa_score_all[4] += float(it['GPA']) * float(it['credit'])
                credit_all[4] += float(it['credit'])
            elif it['termno'] == '9':
                # 大三下
                it.pop('termno')
                it['GPA'] = utils.get_GPA1(int(it['score']))
                result['score_list']['big_3_down']['score'].append(it)
                gpa_score_all[5] += float(it['GPA']) * float(it['credit'])
                credit_all[5] += float(it['credit'])
            elif it['termno'] == '10' or it['termno'] == '11':
                # 大四上
                it.pop('termno')
                it['GPA'] = utils.get_GPA1(int(it['score']))
                result['score_list']['big_4_up']['score'].append(it)
                gpa_score_all[6] += float(it['GPA']) * float(it['credit'])
                credit_all[6] += float(it['credit'])
            else:
                # 大四下
                it.pop('termno')
                it['GPA'] = utils.get_GPA1(int(it['score']))
                result['score_list']['big_4_down']['score'].append(it)
                gpa_score_all[7] += float(it['GPA']) * float(it['credit'])
                credit_all[7] += float(it['credit'])
    for i in range(len(gpa_score_all)):
        result['score_list'][index[i]]['GPA'] = utils.get_GPA(gpa_score_all[i], credit_all[i])
    response = HttpResponse(json.dumps(result))
    response['Access-Control-Allow-origin'] = "*"
    response['Content-Type'] = 'application/json;charset=utf-8'
    return response


# 获取选课信息接口
def get_select_course_info(request):
    res = utils.get_select_course_info()
    result = []
    for it in res:
        it.pop('totalperiod')
        it.pop('assessmethod')
        it.pop('courseattribute')
        it.pop('whetherexam')
        it.pop('termno')
        it.pop('termname')
        it.pop('tmname')
        it.pop('crname')
        course_time = it['course_time']
        sections = utils.split_course_time(course_time)
        it['course_time'] = sections
        result.append(it)
    response = HttpResponse(json.dumps(result))
    response['Access-Control-Allow-origin'] = "*"
    response['Content-Type'] = 'application/json;charset=utf-8'
    return response


def choose_course(request):
    username = ''
    cno = ''
    tno = ''
    if request.method == 'GET':
        username = request.GET.get('username')
        cno = request.GET.get('cno')
        tno = request.GET.get('tno')
    elif request.method == 'POST':
        data_json = json.loads(request.body.decode())
        username = data_json.get('username')
        cno = data_json.get('cno')
        tno = data_json.get('tno')
    res_code = utils.choose_course(username, cno, tno)
    if res_code == 1:
        status_code = 1001
        msg = '学生不存在'
    elif res_code == 2:
        status_code = 1002
        msg = "课程不存在"
    elif res_code == 3:
        status_code = 1003
        msg = "教师不存在"
    elif res_code == 4:
        status_code = 1004
        msg = "选课重复"
    elif res_code == 5:
        status_code = 1005
        msg = "选课冲突"
    else:
        status_code = 1000
        msg = "选课成功"
    result = {
        "status_code": status_code,
        "msg": msg
    }
    response = HttpResponse(json.dumps(result))
    response['Access-Control-Allow-origin'] = "*"
    response['Content-Type'] = 'application/json;charset=utf-8'
    return response


# 获取已选课信息接口
def get_selected_course_info(request):
    username = ''
    if request.method == 'GET':
        username = request.GET.get('username')
    elif request.method == 'POST':
        data_json = json.loads(request.body.decode())
        username = data_json.get('username')
    print(username)
    res = utils.get_selected_course_info(username)
    result = {
        "sno": username,
        "list": []
    }
    for it in res:
        it.pop('sname')
        it.pop('totalperiod')
        it.pop('assessmethod')
        it.pop('courseattribute')
        it.pop('termno')
        it.pop('termname')
        it.pop('crname')
        course_time = it['course_time']
        sections = utils.split_course_time(course_time)
        it['course_time'] = sections
        result["list"].append(it)
    response = HttpResponse(json.dumps(result))
    response['Access-Control-Allow-origin'] = "*"
    response['Content-Type'] = 'application/json;charset=utf-8'
    return response


def exit_course(request):
    username = ''
    cno = ''
    if request.method == 'GET':
        username = request.GET.get("username")
        cno = request.GET.get("cno")
    elif request.method == 'POST':
        data_json = json.loads(request.body.decode())
        username = data_json.get('username')
        cno = data_json.get('cno')
    res = utils.exit_course(username, cno)
    print(username, cno)
    result = {
        "status_code": None,
        "msg": None
    }
    if res == '退课成功':
        result['status_code'] = 1000
        result['msg'] = res
    else:
        result['status_code'] = 1001
        result['msg'] = res
    response = HttpResponse(json.dumps(result))
    response['Access-Control-Allow-origin'] = "*"
    response['Content-Type'] = 'application/json;charset=utf-8'
    return response


def evaluate_teacher(request):
    evaluate_info = ''
    if request.method == 'GET':
        evaluate_info = request.GET.get("evaluate_info")
    elif request.method == 'POST':
        data_json = json.loads(request.body.decode())
        evaluate_info = data_json.get('evaluate_info')
    for it in evaluate_info:
        sno = it['sno']
        tno = it['tno']
        level = it['level']
        query = utils.cursor.execute("select * from EVALUATION where sno='%s' and tno='%s'" % (sno, tno)).fetchall()
        if len(query) == 0:
            # 插入
            res_code = utils.evaluate_teacher(sno, tno, level)
        else:
            # 修改
            utils.cursor.execute("update EVALUATION set EV_LEVE='%s' where sno='%s' and tno='%s'" % (level, sno, tno))
            utils.connection.commit()
    result = {
        "status_code": 1001,
        "msg": "评教完成"
    }
    response = HttpResponse(json.dumps(result))
    response['Access-Control-Allow-origin'] = "*"
    response['Content-Type'] = 'application/json;charset=utf-8'
    return response
